<!--管理员-->
<!--chenyi 2019-09-29 15:30:47-->
<template>
  <div>
    <!--搜索条件-->
    <el-form inline :model="searchParam" ref="searchParam" label-width="80px" class="search-form">
      <el-form-item label="用户名" prop="usernameVague">
        <el-input v-model="searchParam.usernameVague" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickNameVague">
        <el-input v-model="searchParam.nickNameVague" placeholder="请输入昵称" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <es-select v-model="searchParam.status" enum-name="StatusEnum"></es-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchForm">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetSearchForm">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="edit">修改</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="handleInitPassword">重置密码</el-button>
    </el-row>
    <!--表格-->
    <el-table
      border
      :data="tableData"
      v-loading="loading"
      element-loading-text="数据加载中"
      @selection-change="handleSelectionChange"
      class="mt-20">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column
        prop="username"
        label="用户名"
        sortable
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="a-link" @click="detail(scope.row)">{{scope.row.username}}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="nickName"
        label="昵称"
        show-overflow-tooltip>
      </el-table-column>

      <el-table-column
        prop="roleId"
        label="角色"
        show-overflow-tooltip>
      </el-table-column>

      <el-table-column
        prop="deptName"
        label="部门"
        show-overflow-tooltip>
      </el-table-column>

      <el-table-column
        prop="isSys"
        label="是否系统内置"
        width="150">
        <template slot-scope="scope">
          <es-value-format enum-name="WhetherEnum" :value="scope.row.isSys"
                       render-color></es-value-format>
        </template>
      </el-table-column>

      <el-table-column
        prop="status"
        label="状态"
        width="150">
        <template slot-scope="scope">
          <es-value-format enum-name="StatusEnum" :value="scope.row.status"
                       render-color></es-value-format>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        show-overflow-tooltip
        width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="detail(scope.row)">查看
          </el-button>
          <el-button
            size="mini" type="primary"
            @click="edit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            v-if="scope.row.isSys == 0"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      style="margin: 20px;float: right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="searchParam.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--新增修改-->
    <el-dialog :title="title" :visible="action==='add' || action==='edit'" :before-close="handleClose">
      <el-form :model="item" :rules="rules" ref="ruleForm" label-width="100px">
        <div class="form-item-group">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="item.username"
                      placeholder="请输入用户名"
                      maxlength="50"
                      :disabled="action=='edit'"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="item.nickName"
                      placeholder="请输入昵称"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="角色" prop="roleIds">
            <es-select v-model="item.roleIds" url="/admin/role/select" multiple></es-select>
          </el-form-item>

          <el-form-item label="部门" prop="deptId">
            <es-tree v-model="item.deptId" expand-root url="/admin/dept/treeData" ></es-tree>
          </el-form-item>

        </div>
        <div class="form-item-group">
          <el-form-item label="状态" prop="status">
            <es-select v-model="item.status" enum-name="StatusEnum"></es-select>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="item.email"
                      placeholder="请输入邮箱"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="item.mobile"
                      placeholder="请输入手机号"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <es-select v-model="item.gender" enum-name="GenderEnum"></es-select>
          </el-form-item>

        </div>

        <el-form-item label="头像" prop="headPic">
          <es-upload-img
            :value="item.headPic"
            @success="uploadSuccess"
          ></es-upload-img>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="action = 'list'">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--详情页-->
    <el-dialog :title="title" :visible="action==='info'" :before-close="handleClose">
      <el-form :model="item" label-width="100px">
        <div class="form-item-group">
          <el-form-item label="用户名" prop="username">
            <span>{{item.username||"-"}}</span>
          </el-form-item>
          <el-form-item label="姓名" prop="nickName">
            <span>{{item.nickName||"-"}}</span>
          </el-form-item>
          <el-form-item label="头像" prop="headPic">
            <es-preview-img v-model="item.headPic"></es-preview-img>
          </el-form-item>
          <el-form-item label="系统内置" prop="isSys">
            <es-value-format :value="item.isSys" enum-name="WhetherEnum" render-color></es-value-format>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <es-time type="format" :value="item.createTime"></es-time>
          </el-form-item>
          <el-form-item label="状态:" >
            <es-value-format enum-name="StatusEnum" :value="item.status" render-color></es-value-format>
          </el-form-item>
        </div>
        <div class="form-item-group">
          <el-form-item label="邮箱" prop="email">
            <span>{{item.email||"-"}}</span>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <span>{{item.mobile||"-"}}</span>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <es-value-format :value="item.gender" enum-name="GenderEnum"></es-value-format>
          </el-form-item>
          <el-form-item label="qq" prop="qq">
            <span>{{item.qq||"-"}}</span>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <span>{{item.roleId||"-"}}</span>
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <span>{{item.deptName||"-"}}</span>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="action = 'list'">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getList, save, update, remove,initPassword} from '../../api/sys/userApi'
  import validate from '../../libs/validate'
  import EsValueFormat from "../../components/public/es-value-format";

  export default {
    components: {EsValueFormat},
    name: 'user',
    data() {
      return {
        searchParam: {//表格数据请求参数
          page: 1,
          limit: 10
        },
        title: '',
        action: 'list',
        loading: false,
        item: {},  //修改/详情数据
        rules: {  //表单验证
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: '请输入昵称', trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        },
        multipleSelection: [], //复选框选中的值
        tableData: [],
        total: 0,
        ids: []
      }
    },
    created() {

    },
    mounted() {
      //获取数据
      this.getTableData()
    },
    methods: {
      //头像上传成功
      uploadSuccess: function (res) {
        this.item.headPic = res;
      },
      handleInitPassword(){
        let ids = this.getSelectIds();
        if(ids.length === 0){
          return false;
        }
        initPassword(ids).then(res=>{
          if (res.code === 200) {
            this.$message.success("操作成功")
          } else {
            this.$message.error(res.msg)
          }
        });
      },
      //获取数据
      getTableData() {
        let _this = this
        _this.loading = true
        getList(_this.searchParam).then((res) => {
          if (res.code === 200) {
            _this.tableData = res.data
            console.log(_this.tableData)
            _this.total = res.total
          } else {
            this.$message.error(res.msg)
          }
          _this.loading = false
        })
      },
      //提交表单
      submitForm() {
        let _this = this
        _this.$refs['ruleForm'].validate(function (valid) {
          if (valid) {
            //保存
            if (_this.action === 'add') {
              save(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('新增成功！')
                  _this.getTableData();
                  _this.action = 'list';
                } else {
                  _this.$message.error(res.msg)
                }

              })
            }
            //修改
            else if (_this.action === 'edit') {
              update(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('修改成功！')
                  _this.getTableData()
                } else {
                  _this.$message.error(res.msg)
                }
                _this.action = 'list'
              })
            }
          }
        })
      },
      //删除
      handleDelete: function (index, row) {
        let temp = Object.assign({}, row);
        //获取选中的id
        let ids = this.getSelectIds(temp);
        if (ids.length > 0) {
          this.ids = ids;
          //删除数据
          let _this = this;
          _this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: function (action, instance) {
              if (action === "confirm") {
                remove(_this.ids).then((res) => {
                  if (res.code === 200) {
                    //刷新表格数据
                    _this.getTableData();
                    _this.$message.success("删除成功!");
                  }
                  else {
                    _this.$message.error(res.msg);
                  }
                })
                ;
              }
            }
          })
        }
      },
      add() {
        this.item = {}
        this.action = 'add'
        this.title = '新增管理员'
      },
      //修改页面
      edit: function (index, row) {
        let _this = this
        let temp = Object.assign({}, row)
        if (Object.keys(temp).length === 0) {
          let chcekeds = _this.multipleSelection
          if (chcekeds.length === 0) {
            _this.$message.error('请选择一条数据')
            return false
          } else if (chcekeds.length > 1) {
            _this.$message.error('只能选择一条数据')
            return false
          } else {
            _this.item = chcekeds[0]
          }
        } else {
          _this.item = temp
        }
        _this.action = 'edit'
        _this.title = '修改管理员'
        _this.currentIndex = index;
      },
      detail(row){
        this.item = row;
        this.action='info';
      },
      handleClose(done) {
        this.action = 'list'
        done()
      },
      //获取选中行
      getSelectIds: function (row) {
        let chcekeds = [];
        let ids = [];
        if (!row || Object.keys(row).length === 0) {
          chcekeds = this.multipleSelection;
          if (chcekeds.length === 0) {
            this.$message.error("至少选择一条数据");
          } else {
            for (let key in chcekeds) {
              ids.push(chcekeds[key].userId);
            }
          }
        } else {
          ids.push(row.userId);
        }
        return ids;

      },
      //查询表格
      searchForm() {
        this.searchParam.page = 1
        //获取数据
        this.getTableData()
      },
      //重置查询表格
      resetSearchForm() {
        this.$refs['searchParam'].resetFields()
        //获取数据
        this.getTableData()
      },
      handleSizeChange(limit) {
        this.searchParam.limit = limit
        //获取数据
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.searchParam.page = page
        //获取数据
        this.getTableData()
      },
      //复选框选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
    }
  }
</script>

<style scoped>

</style>
